/**
 * Created by zhulizhe on 2017/8/30.
 */
import React, {Component} from 'react';
import {
    Text,
    View,
    TouchableOpacity,
    TextInput,
    StyleSheet,
    ScrollView,
    Dimensions,
    Image
} from 'react-native';
import Constant from '../../js/Contant'
import {observable, action, computed, observe} from 'mobx'
import {observer} from 'mobx-react/native'
import Ionicons from 'react-native-vector-icons/Ionicons';
import LinearGradient from "react-native-linear-gradient";
import {GradientButton} from "../../js/component/Button";
import RequestUtil from "../../js/util/NetUtil";

const TOTALCOUNT = 60;
import loginStore from '../store/LoginStoreLuo'
import NumberUtil from "../../js/util/NumberUtil";
import Toast from 'react-native-easy-toast'
import * as WeChat from 'react-native-wechat'
import {SafeAreaView} from "react-navigation";
import BindPhoneNum from "./SendCheckCode";
import {ResetRouter} from "../../js/router/RouterUtil";

const ScreenW = Dimensions.get('window').width;
const Input = ({value,title='', placeholder, onChangeText, keyboardType = 'default', secureTextEntry = false}) => {
    return <View style={{height:50.5}}>
        <View style={{flexDirection:'row',alignItems:'center',paddingHorizontal:15,height:50,backgroundColor:'white'}}>
            <View style={{flex:1}}>
                <Text style={{fontSize:14,color:'rgba(51,51,51,1)'}}>{title}</Text>
            </View>
            <View style={[{marginLeft:10,height:40,backgroundColor:'white',flex:5}]}>
                <TextInput
                    underlineColorAndroid='transparent'
                    clearTextOnFocus={true}
                    style={{fontSize:14,fontWeight:'400',height:40,color:'rgba(51,51,51,1)'}}
                    value={value}
                    keyboardType={keyboardType}
                    secureTextEntry={secureTextEntry}
                    placeholder={placeholder}
                    onChangeText={onChangeText}/>
            </View>
        </View>
        <View style={{flexDirection:'row',marginLeft:12,width:ScreenW-24,height:0.5,backgroundColor:'rgba(217,217,217,1)'}}/>
    </View>
}

const Header = ({navigation, title}) => {
    return <LinearGradient
        colors={['#14c2fc', '#399cfc']}
        style={{
            height: 80,
            paddingTop: 20,
            flexDirection: 'row',
            justifyContent: 'space-between',
            alignItems: 'center'
        }}>
        <View style={{flex: 1}}>
            <TouchableOpacity
                onPress={() => {
                    navigation.goBack();
                }}
                style={{backgroundColor: '#00000000', paddingHorizontal: 20}}
                activeOpacity={0.8}>
                <Ionicons name="ios-close-outline" color="#fff" size={40}/>
            </TouchableOpacity>
        </View>
        <View style={{flex: 2}}>
            <Text style={{
                fontSize: Constant.FONT_SIZE_36,
                backgroundColor: '#00000000',
                fontWeight: '500',
                color: '#fff',
                alignSelf: 'center'
            }}>{title}</Text>
        </View>
        <View style={{flex: 1}}/>
    </LinearGradient>
}

const Footer = ({navigation}) => {
    return <TouchableOpacity
        onPress={() => {
            navigation.navigate('Protocol');
        }}
        style={{padding: 15}}>
        <Text>登录即为同意<Text style={{color: Constant.BLUECOLOR}}>《汇贝软件许可及服务协议》</Text></Text>
    </TouchableOpacity>
}

const LoginBtn = ({onPress})=>{
    return  <View style={{justifyContent:'space-between',alignItems:'center',height: 70,marginTop:20}}>
        <TouchableOpacity style={{justifyContent:'center',alignItems:'center',width:ScreenW-30,height:40,backgroundColor:'#14c2fc'}}
                          onPress={onPress}>
            <Text style={{fontSize:15,color:'white'}}>登录</Text>
        </TouchableOpacity>
        {/*<TouchableOpacity>*/}
        {/*<Text style={{fontSize:13,color:'rgba(119,119,119,1)'}}>忘记密码？</Text>*/}
        {/*</TouchableOpacity>*/}
    </View>
}

const LoginHeaderOld = () => {
    return <View>
        <View style={{flexDirection: 'row', alignItems: 'center', backgroundColor: '#fff'}}>
            <View style={{flex: 3}}>
                <Input
                    keyboardType="phone-pad"
                    placeholder="手机号"
                    value={this.decoratePhoneNum}
                    onChangeText={(text) => {
                        this.phoneNum = text;
                        this.decoratePhoneNum = text.replace(/(\d{3})(\d{4})/, "$1-$2-");
                    }}/>
            </View>
            <View style={{flex: 1, alignItems: 'center'}}>
                <View style={{alignItems: 'center'}}>
                    <TouchableOpacity
                        onPress={this.startCount.bind(this)}
                        activeOpacity={0.8}
                        style={{
                            alignItems: 'center',
                            justifyContent: 'center',
                            backgroundColor: this.decoratePhoneNum.length == 13 && !this.waiting ? Constant.BLUECOLOR : Constant.TEXT_COLOR_F3,
                            height: 30,
                            width: 90,
                            borderRadius: 4
                        }}>
                        <Text style={{
                            color: this.decoratePhoneNum.length == 13 && !this.waiting ? '#fff' : Constant.TEXT_COLOR_9,
                            fontSize: Constant.FONT_SIZE_28
                        }}>{this.waiting ? this.remainCount + 's后重试' : '获取验证码'}</Text>
                    </TouchableOpacity>
                </View>
            </View>
        </View>
        <View>
            <Input
                placeholder="验证码"
                onChangeText={(text) => {
                    this.checkCode = text;
                }}/>
        </View>
        <LoginBtn/>
        <Footer
            navigation={this.props.navigation}
        />
    </View>
}

const HBIcon = () => {
    return <View style={{alignItems: 'center',paddingVertical:10}}>
        <Image style={{width: 60, height: 60}} source={require('../../luoasserts/icon/icon.png')}/>
    </View>
}
const LoginHeader = ({navigation,onUserNameChange,onPwdChange,onSubmit}) => {
    return <View style={{paddingVertical: 10}}>
        <HBIcon/>
        <Input
            title='账号'
            keyboardType="phone-pad"
            placeholder="请输入手机号"
            value={this.decoratePhoneNum}
            onChangeText={onUserNameChange}/>
        <Input
            title='密码'
            placeholder="请输入密码"
            value={this.decoratePhoneNum}
            onChangeText={onPwdChange}/>
        <LoginBtn onPress={onSubmit}/>
    </View>
}


@observer
export default class Login extends Component {

    @observable phoneNum = '';
    @observable password = null ;
    @observable decoratePhoneNum = '';

    @observable checkCode = '';

    @observable remainCount = TOTALCOUNT;
    @observable waiting = false;

    static navigationOptions = ({navigation}) => ({
        // header:<Header navigation={navigation} title="登录"/>,
        headerStyle: {
            backgroundColor: '#fff'
        }
    })

    constructor(props) {
        super(props)
        this.goBack = this.goBack.bind(this);
    }

    // 开始倒计时
    startCount() {
        if (this.waiting) return;
        if (this.phoneNum.length != 13) return;
        let phone = NumberUtil.removeDecoratePhoneNumber(this.phoneNum);
        // 在此请求发送验证码
        RequestUtil.requestData('checkCode/login', {
            phoneNum: phone
        }).then((result) => {
            this.waiting = true;
            this.timer = setInterval(() => {
                this.remainCount -= 1;
                if (this.remainCount == 0) {
                    this.remainCount = TOTALCOUNT;
                    this.waiting = false;
                    this.clearTimer();
                }
            }, 1000);
        })
    }

    // 清除倒计时
    clearTimer() {
        this.timer && clearInterval(this.timer);

    }

    goBack() {
        this.props.navigation.goBack();

    }

    // 登录
    login() {
        if(this.phoneNum==''||this.password==null){
            LOG('登录为空-------');
            return;
        }
        let navigation = this.props.navigation ;
        RequestUtil.requestData('login/byPassword',{
            phoneNum:this.phoneNum,
            password:this.password
        }).then(token=>{
            LOG('登录----------'+JSON.stringify(token));
            loginStore.wxUpdate(this.phoneNum, token.access_token, token.access_secret).then((data)=>{
                LOG('账号登录-------'+JSON.stringify(data));
                ResetRouter(navigation);
            });
        }).catch(err=>{
            LOG('登录错误----------'+JSON.stringify(err));
            this.refs.toast.show(err);
        });
    }

    wechatLogin(){
        let navigation = this.props.navigation ;
        WeChat.sendAuthRequest("snsapi_userinfo").then(userinfo => {
            let code = userinfo.code;
            console.log('code###', code);
            RequestUtil.requestData('login/weixin', {
                code: code
            }).then(data => {
                LOG('微信登录-------'+JSON.stringify(data));
                let token = data.accessToken;
                if (token) {
                    loginStore.wxUpdate('', token.access_token, token.access_secret).then(resolve=>{
                        let nextStep = data.nextStep;
                        if (nextStep) {
                            if (nextStep == 'mainPage') {
                                ResetRouter(navigation);
                            }
                            else if (nextStep == 'bindPhoneNum') {
                                this.props.navigation.navigate('SendCheckCode');
                            }
                        }
                    });
                }

            }).catch(err => {
                //alert(err);
            })
        });
    }

    render() {
        let navigation = this.props.navigation ;
        return <SafeAreaView style={{flex: 1}}>
            <ScrollView contentContainerStyle={{flex: 1, backgroundColor: '#fff', justifyContent: 'space-between'}}>
                <LoginHeader
                    onUserNameChange={(text)=>{
                        this.phoneNum = text ;
                    }}
                    onPwdChange={text=>{
                        this.password = text ;
                    }}
                    onSubmit={this.login.bind(this)}
                    navigation={this.props.navigation}/>
                {/*<LoginHeaderOld/>*/}
                <View>
                    <WeChatBtn onPress={this.wechatLogin.bind(this)}/>
                </View>
            </ScrollView>
            <Toast ref="toast" position='center'/>
        </SafeAreaView>
    }
}

const WeChatBtn = ({onPress}) => {
    return <View style={{alignItems:'center',height:180}}>
        <View style={{flexDirection:'row',flex:1,justifyContent:'space-between',alignItems:'center',width:ScreenW}}>
            <View style={{marginLeft:14,backgroundColor:'rgba(217,217,217,1)',width:(ScreenW-72)/2,height:0.5}}/>
            <Text style={{width:16,fontSize:13,color:'rgba(119,119,119,1)'}}>或</Text>
            <View style={{marginRight:14,backgroundColor:'rgba(217,217,217,1)',width:(ScreenW-72)/2,height:0.5}}/>
        </View>
        <View style={{justifyContent:'center',alignItems:'center',height:167}}>
            <TouchableOpacity style={{justifyContent:'space-between',alignItems:'center',width:145,height:85,backgroundColor:'white'}}
                              onPress={onPress}>
                <Image style={{width:55,height:55}} source={require('../../asserts/shop/icon_wechat.png')}/>
                <Text style={{fontSize:13,color:'#14c2fc'}}>微信安全登录/注册</Text>
            </TouchableOpacity>
        </View>

    </View>
}

const styles = {
    borderBottom: {
        borderBottomColor: Constant.SEPLINECOLOR,
        borderBottomWidth: StyleSheet.hairlineWidth
    },
}

